package com.zhugang.week02;

import java.util.Stack;

/**
 * @program algorithms
 * @description: palindromeList
 * @author: chanzhugang
 * @create: 2022/05/30 17:11
 */
public class PalindromeList {

    /**
     * 234. 回文链表
     *
     * @param head
     * @return
     */
    public boolean isPalindrome(ListNode head) {
        // 遍历链表，将节点值放入栈； 遍历head，比较节点值和出栈值
        Stack<Integer> stack = new Stack<>();
        ListNode cur = head;
        while (cur != null) {
            stack.push(cur.val);
            cur = cur.next;
        }
        while (head != null) {
            if (head.val != stack.pop()) {
                return false;
            } else {
                head = head.next;
            }
        }
        return true;
    }

    public boolean isPalindrome2(ListNode head) {
        // 1、找中间链表；2、反转中间链表之后的链表；比较反转后的链表和原链表一半
        if (head == null || head.next == null) {
            // 链表为空，或者只有一个节点
            return true;
        }
        ListNode midNode = findMiddleNode(head);
        ListNode rightHalfHead = reverseList(midNode.next);
        ListNode p = head;
        ListNode q = rightHalfHead;
        while (q != null) {
            if (p.val != q.val) {
                return false;
            } else {
                p = p.next;
                q = q.next;
            }
        }
        return true;
    }

    private ListNode reverseList(ListNode head) {
        if (head == null) {
            return null;
        }
        // 反转链表，开辟新链表，每次遍历反转一次， p.next = new; new = p;
        ListNode newNode = null;
        ListNode p = head;
        while (p != null) {
            ListNode temp = p.next;
            p.next = newNode;
            newNode = p;
            p = temp;
        }
        return newNode;

    }

    private ListNode findMiddleNode(ListNode head) {
        // 快慢指针，慢指针每次走一步，快指针每次走两步
        ListNode slow = head;
        ListNode fast = head;
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }


    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

}